package com.wsc.wisdomchinaqinghe.activitity.fourmodule;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.wsc.wisdomchinaqinghe.R;
import com.wsc.wisdomchinaqinghe.Tools.AbPermissionUtils;
import com.wsc.wisdomchinaqinghe.Tools.BitmapUtils;
import com.wsc.wisdomchinaqinghe.Tools.JsonTools;
import com.wsc.wisdomchinaqinghe.activitity.baseactivity.BaseActivity;
import com.wsc.wisdomchinaqinghe.callback.ContributorView;
import com.wsc.wisdomchinaqinghe.constant.Constant;
import com.wsc.wisdomchinaqinghe.javaBean.CsOldAgePensionBean;
import com.wsc.wisdomchinaqinghe.javaBean.RespObj;
import com.wsc.wisdomchinaqinghe.presenter.ContributorPresenter;
import com.wsc.wisdomchinaqinghe.view.MyToast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 失業登記页面
 * Created by ${wangtao} on 2017/3/6.
 */

public class PensionPublishPhotoActivity extends BaseActivity implements View.OnClickListener,ContributorView{

    private String uid;
    private int type;
    private int subType;
    private String cid;
    private CsOldAgePensionBean csOldAgePensionBean;
    private Context context;
    private ImageView regist_back;
    private TextView tv_headtitle;
    private ImageView iv_shenfenzhengpositive;
    private ImageView iv_shenfenzhengnegative;
    private ImageView iv_hukoubenfirst;
    private ImageView iv_hukoubensecond;
    private ImageView iv_yinhangka;
    private Button bt_submit;
    private TextView tv_cancelPhone;
    private TextView tv_takephoto;
    private TextView tv_photo;
    private PopupWindow popupWindowPhone;
    private View mpopupWindowViewPhone;
    private int imageFlag = 1;
    private Bitmap photo;
    private MyToast myToast;
    private String paramsOne;
    private String paramsTwo;
    private String paramsThree;
    private String paramsFour;
    private String paramsFive;
    private ContributorPresenter contributorPresenter;
    private String UPLOADFLAG="UPLOADFLAG";
    private String previousId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pensionpublishphoto_layout);
        context=this;
        contributorPresenter = new ContributorPresenter(this, context);
        myToast=new MyToast(context);
        Intent intent=getIntent();
        uid=intent.getStringExtra("uid");
        type=intent.getIntExtra("type",10);
        subType=intent.getIntExtra("subType",0);
        cid=intent.getStringExtra("cid");
        previousId=intent.getStringExtra("previousId");
        csOldAgePensionBean=(CsOldAgePensionBean) intent.getSerializableExtra("object");
        initView();
        initPopupWindowPhone();
    }

    private void initView()
    {
        regist_back=(ImageView) findViewById(R.id.regist_back);
        tv_headtitle=(TextView) findViewById(R.id.tv_headtitle);
        tv_headtitle.setText("尊老金发放审批表(2/2)");
        regist_back.setOnClickListener(this);
        iv_shenfenzhengpositive=(ImageView) findViewById(R.id.iv_shenfenzhengpositive);
        iv_shenfenzhengnegative=(ImageView) findViewById(R.id.iv_shenfenzhengnegative);
        iv_hukoubenfirst=(ImageView) findViewById(R.id.iv_hukoubenfirst);
        iv_hukoubensecond=(ImageView) findViewById(R.id.iv_hukoubensecond);
        iv_yinhangka=(ImageView) findViewById(R.id.iv_yinhangka);
        bt_submit=(Button) findViewById(R.id.bt_submit);

        iv_shenfenzhengpositive.setOnClickListener(this);
        iv_shenfenzhengnegative.setOnClickListener(this);
        iv_hukoubenfirst.setOnClickListener(this);
        iv_hukoubensecond.setOnClickListener(this);
        iv_yinhangka.setOnClickListener(this);
        bt_submit.setOnClickListener(this);
    }

    /**
     * 初始化popupwindow
     */
    private void initPopupWindowPhone() {
        mpopupWindowViewPhone = LayoutInflater.from(getApplicationContext()).inflate(R.layout.headinfo, null);
        popupWindowPhone = new PopupWindow(mpopupWindowViewPhone, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);// 全屏显示，将内容设置在底部
        popupWindowPhone.setFocusable(true);
        popupWindowPhone.setBackgroundDrawable(new BitmapDrawable());

        tv_cancelPhone = (TextView) mpopupWindowViewPhone.findViewById(R.id.tv_cancel);
        tv_cancelPhone.setOnClickListener(this);
        tv_takephoto = (TextView) mpopupWindowViewPhone.findViewById(R.id.tv_takephoto);
        tv_takephoto.setOnClickListener(this);
        tv_photo = (TextView) mpopupWindowViewPhone.findViewById(R.id.tv_photo);
        tv_photo.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.regist_back:
                finish();
                break;
            // 取消点击事件
            case R.id.tv_cancel:
                popupWindowPhone.dismiss();
                break;
            // 拍照点击事件
            case R.id.tv_takephoto:
                popupWindowPhone.dismiss();
                try {
                    AbPermissionUtils.requestPermissionsResult(this, 1
                            , new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                            }
                            , new AbPermissionUtils.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {

                                    Uri uri = getUri();
                                    Intent intent = new Intent();
                                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//将拍取的照片保存到指定URI
                                    startActivityForResult(intent,6);
                                }

                                @Override
                                public void onPermissionDenied() {

                                }
                            });
                }catch (Exception e)
                {
                    myToast.showShort("拍照失败");
                }
                break;
            // 用户相册点击事件
            case R.id.tv_photo:
                popupWindowPhone.dismiss();
                try{
                    AbPermissionUtils.requestPermissionsResult(this, 1
                            , new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                            }
                            , new AbPermissionUtils.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {
                                    Intent intentphoto = new Intent(Intent.ACTION_PICK, null);
                                    intentphoto.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                    startActivityForResult(intentphoto, 1);
                                }

                                @Override
                                public void onPermissionDenied() {

                                }
                            });
                }catch (Exception e)
                {
                    myToast.showShort("读取相册失败");
                }
                break;
            //身份证正面
            case R.id.iv_shenfenzhengpositive:
                imageFlag=1;
                if (!popupWindowPhone.isShowing()) {
                    popupWindowPhone.showAtLocation(findViewById(R.id.iv_shenfenzhengpositive), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowPhone.dismiss();
                }
                break;
            //身份证反面
            case R.id.iv_shenfenzhengnegative:
                imageFlag=2;
                if (!popupWindowPhone.isShowing()) {
                    popupWindowPhone.showAtLocation(findViewById(R.id.iv_shenfenzhengnegative), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowPhone.dismiss();
                }
                break;
            //户口本首页
            case R.id.iv_hukoubenfirst:
                imageFlag=3;
                if (!popupWindowPhone.isShowing()) {
                    popupWindowPhone.showAtLocation(findViewById(R.id.iv_hukoubenfirst), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowPhone.dismiss();
                }
                break;
            //户口本本人页
            case R.id.iv_hukoubensecond:
                imageFlag=4;
                if (!popupWindowPhone.isShowing()) {
                    popupWindowPhone.showAtLocation(findViewById(R.id.iv_hukoubensecond), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowPhone.dismiss();
                }
                break;
            //银行卡
            case R.id.iv_yinhangka:
                imageFlag=5;
                if (!popupWindowPhone.isShowing()) {
                    popupWindowPhone.showAtLocation(findViewById(R.id.iv_yinhangka), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowPhone.dismiss();
                }
                break;
            //审核提交
            case R.id.bt_submit:
                if(paramsOne==null||paramsTwo==null||paramsThree==null||paramsFour==null||paramsFive==null)
                {
                    myToast.showShort("证件照片不能为空");
                }else
                {
                    String params="idFrontImg"+","+"idBackImg"+","+"familyRegisterHomePageImg"+","+"familyRegisterSelfPageImg"+","+"validBankBookImg";
                    String pic=paramsOne+","+paramsTwo+","+paramsThree+","+paramsFour+","+paramsFive;
                    contributorPresenter.getUploadCommonParamsPicList(params,pic,UPLOADFLAG);
                }
                break;
        }
    }
    @Override
    public void onLoadContributorStart(String flag) {
        if (flag.equals(UPLOADFLAG)) {
            myToast.showShort("证件图片提交审核中...");
            bt_submit.setEnabled(false);
        }
    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        try {
            //发送验证码
            if (flag.equals(UPLOADFLAG)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code=respObj.getCode();
                if(code.equals("200"))
                {
                    String message=JsonTools.objectToJsonString(respObj.getMessage());
                    CsOldAgePensionBean csOldAgePensionBeanparams=JsonTools.jsonStringToObject(message,CsOldAgePensionBean.class);
                    if(csOldAgePensionBeanparams!=null)
                    {
                        csOldAgePensionBean.setIdFrontImg(csOldAgePensionBeanparams.getIdFrontImg());
                        csOldAgePensionBean.setIdBackImg(csOldAgePensionBeanparams.getIdBackImg());
                        csOldAgePensionBean.setFamilyRegisterHomePageImg(csOldAgePensionBeanparams.getFamilyRegisterHomePageImg());
                        csOldAgePensionBean.setFamilyRegisterSelfPageImg(csOldAgePensionBeanparams.getFamilyRegisterSelfPageImg());
                        csOldAgePensionBean.setValidBankBookImg(csOldAgePensionBeanparams.getValidBankBookImg());

                        Intent intent=new Intent(context,PensionPublishSignActivity.class);
                        intent.putExtra("uid",uid);
                        intent.putExtra("type",type);
                        intent.putExtra("subType",subType);
                        intent.putExtra("cid",cid);
                        intent.putExtra("object",csOldAgePensionBean);
                        intent.putExtra("previousId",previousId);
                        startActivityForResult(intent,0);

                    }
                }else
                {
                    myToast.showShort("提交失败");
                }
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onLoadContributorComplete(String flag) {
        if(flag.equals(UPLOADFLAG))
        {
            bt_submit.setEnabled(true);
            myToast.cancel();
        }
    }

    @Override
    public void onLoadContributorError(String error,String flag) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // 从相册里面获取
            case 1:
                if (data != null && data.getData() != null) {
                    startPhotoZoom(data.getData());
                }
                break;
            // 裁剪
            case 2:
                if (data != null) {
                    setPicToView(data);
                }
                break;
            // 拍照
            case 6:
                startPhotoZoomCut();
                break;
            case 0:
                if(resultCode==1) {
                    Intent intent=getIntent();
                    setResult(1,intent);
                    finish();
                }
                break;
        }
    }
    private Uri getUri() {
        try{
            File cacheDir;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                cacheDir = new File(Environment.getExternalStorageDirectory(), Constant.wsc_photo);
            else
                cacheDir = context.getCacheDir();
            if (!cacheDir.exists())
                cacheDir.mkdirs();

            File path = new File(cacheDir, "");
            if (!path.exists()) {
                path.mkdirs();
            }
            File file = new File(path, "pensionpublish.jpg");
            //由于一些Android 7.0以下版本的手机在剪裁保存到URI会有问题，所以根据版本处理下兼容性
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return FileProvider.getUriForFile(context, "com.wsc.wisdomchinaqinghe.fileprovider", file);
            } else {
                return Uri.fromFile(file);
            }
        }catch (Exception e)
        {
            return null;
        }

    }

    /**
     * @param uri
     * @Description 裁剪图片
     * @author jaily.zhang
     */
    private void startPhotoZoom(Uri uri) {
        try {
                 /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
		 * yourself_sdk_path/docs/reference/android/content/Intent.html
		 * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能, 是直接调本地库的，小马不懂C C++
		 * 这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么 制做的了...吼吼
		 */
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 0.8);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 2);
        } catch (Exception e) {

        }
    }

    /**
     * 裁剪图片从拍照
     */
    private void startPhotoZoomCut()
    {
        try {
            Uri uri = getUri();
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            intent.setDataAndType(uri , "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 0.8);
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("scale", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, getUri());
            intent.putExtra("return-data", true);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("noFaceDetection", true);

            //将存储图片的uri读写权限授权给剪裁工具应用
            List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            startActivityForResult(Intent.createChooser(intent, "选择剪裁工具"), 2);
        } catch (Exception e) {

        }
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            photo = extras.getParcelable("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            if (photo != null) {
                try {
                    // Drawable drawable = new BitmapDrawable(photo);

                    /**
                     * 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上 传到服务器，QQ头像上传采用的方法跟这个类似
                     */

                    int options = 70;
                    photo.compress(Bitmap.CompressFormat.JPEG, options, stream);
                    byte[] b = stream.toByteArray();// 将图片流以字符串形式存储下来
                    // 大于2KB
                    while (b.length > 5 * 1024) {
                        stream.reset();// 清空流
                        options -= 10;
                        photo.compress(Bitmap.CompressFormat.JPEG, options, stream);
                        b = stream.toByteArray();
                    }

                    Message message=new Message();
                    message.what=imageFlag;
                    mHandler.sendMessage(message);

                } catch (Exception e) {

                } finally {
                    try {
                        // 关闭流
                        stream.flush();
                        stream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        }
    }

    // handler 消息处理
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //身份证正面
                case 1:
                    Drawable drawable = new BitmapDrawable(photo);
                    iv_shenfenzhengpositive.setImageDrawable(drawable);
                    paramsOne= BitmapUtils.bitmapToBase64(photo);
                    break;
                //身份证背面
                case 2:
                    Drawable drawable2 = new BitmapDrawable(photo);
                    iv_shenfenzhengnegative.setImageDrawable(drawable2);
                    paramsTwo= BitmapUtils.bitmapToBase64(photo);
                    break;
                //户口本首页
                case 3:
                    Drawable drawable3 = new BitmapDrawable(photo);
                    iv_hukoubenfirst.setImageDrawable(drawable3);
                    paramsThree= BitmapUtils.bitmapToBase64(photo);
                    break;
                //户口本本人页
                case 4:
                    Drawable drawable4 = new BitmapDrawable(photo);
                    iv_hukoubensecond.setImageDrawable(drawable4);
                    paramsFour= BitmapUtils.bitmapToBase64(photo);
                    break;
                //存折
                case 5:
                    Drawable drawable5 = new BitmapDrawable(photo);
                    iv_yinhangka.setImageDrawable(drawable5);
                    paramsFive= BitmapUtils.bitmapToBase64(photo);
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(photo!=null && !photo.isRecycled())
        {
            photo.isRecycled();
            photo=null;
        }
    }

}
